<?php
namespace Tbf\Component\Http;
use Guzzle\Common\Event;
use Guzzle\Http\Client;
use Guzzle\Http\ClientInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Tbf\Bundle\TbfBundle\Service\SymfonyKernelFactory;

/**
 * 在symfony的框架内部发送ajax,
 */
class SymfonyAjax extends Ajax
{
    protected $kernel_factory;
    protected $session;
    public function __construct(SymfonyKernelFactory $kernel_factory,ClientInterface $client)
    {
        parent::__construct($client);
        $this->kernel_factory = $kernel_factory;
        $dispatch = $client->getEventDispatcher();
        $dispatch->addListener('request.before_send',array($this,'onBeforeSend'),-1001);
        $this->reset();
    }
    public function onBeforeSend(Event $event)
    {
        $guzzle_request = $event['request'];
        $symfony_request = Adapter::guzzleToSymfonyRequest($guzzle_request);

        //see \Symfony\Component\HttpFoundation\Request::hasPreviousSession need to set cookie
        $symfony_request->setSession($this->session);
        $symfony_request->cookies->set('TBFTESTSESSIONID','abc');

        Adapter::dumpSymfonyRequestToPhpGlobal($symfony_request);
        $kernel = $this->kernel_factory->newKernel();

        $kernel->boot();
        $kernel->getContainer()->set('session',$this->session);
        $symfony_response = $kernel->handle($symfony_request);
        $kernel->getContainer()->get('doctrine')->getManager()->clear();

        $kernel->terminate($symfony_request,$symfony_response);
        $kernel->shutdown();
        $guzzle_response = Adapter::symfonyToGuzzleResponse($symfony_response);

        unset($symfony_request,$symfony_response,$kernel);

        $guzzle_request->setResponse($guzzle_response);
        $event->stopPropagation();

        return;
    }
    public function reset()
    {
        $this->session = new Session(new MockArraySessionStorage('TBFTESTSESSIONID'));
    }
}
